﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing.Design;

namespace DnnSun.WebControls.Toolkit
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:ColorPicker runat=server></{0}:ColorPicker>")]
    [ToolboxBitmap(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.color_picker_icon.jpg")]
    public class ColorPicker : WebControl, IPostBackDataHandler
    {
        public event EventHandler ColorChanged;

        private string DEFAULT_PICKERIMAGE_STYLE = @"float:left;margin-left:5px;cursor:hand;border:none;margin-top:2px;";

        private string color;

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("#000000")]
        [Localizable(true)]
        public string Color
        {
            get
            {
                return color;
                //String s = (String)ViewState["Color"];
                //return ((s == null) ? "#000000" : s);
            }

            set
            {
                //ViewState["Color"] = value;
                color = value;
            }
        }

        [Themeable(false)]
        [Category("Behavior")]
        [DefaultValue(false)]
        public virtual bool AutoPostBack
        {
            get
            {
                object obj2 = this.ViewState["AutoPostBack"];
                return ((obj2 != null) && ((bool)obj2));
            }
            set
            {
                this.ViewState["AutoPostBack"] = value;
            }
        }

        [DefaultValue("")]
        [Editor("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [UrlProperty]
        [Description("ColorPicker_ImageUrl")]
        [Bindable(true)]
        [Category("Appearance")]
        public virtual string PickerImageURL
        {
            get
            {
                string str = (string)this.ViewState["PickerImageURL"];
                if (!string.IsNullOrEmpty(str))
                {
                    return this.ResolveClientUrl(str);
                }

                return Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.color_picker_icon.jpg"); ;
            }
            set
            {
                this.ViewState["PickerImageURL"] = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnPreRender(e);
            // Javascript
            string colorFunctions = Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.Javascript.color_functions.js");
            Page.ClientScript.RegisterClientScriptInclude("color_functions.js", colorFunctions);
            string colorPicker = Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.Javascript.js_color_picker_v2.js");
            Page.ClientScript.RegisterClientScriptInclude("js_color_picker_v2.js", colorPicker);

            //images
            string script = string.Format(@"
            var form_widget_amount_slider_handle = '{0}';
            var tab_right_active = '{1}';
            var tab_right_inactive = '{2}';
            var tab_left_active = '{3}';
            var tab_left_inactive = '{4}';
            ", Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.slider_handle.gif")
             , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.tab_right_active.gif")
             , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.tab_right_inactive.gif")
             , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.tab_left_active.gif")
             , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.images.tab_left_inactive.gif")
             );
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "initColorPicker", script, true);

            // CSS
            if (Page.Header.FindControl("Toolkit_ColorPicker_Style") == null)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.ID = "Toolkit_ColorPicker_Style";
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), "DnnSun.WebControls.Toolkit.Styles.js_color_picker_v2.css"));
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                Page.Header.Controls.Add(csslink);
            }

            // Generating AutoPostBack Code
            if (this.AutoPostBack == true)
            {
                string strPostBackCode = this.Page.ClientScript.GetPostBackEventReference(this, "");
            }
            //if (Page.IsPostBack)
            //    Color = Page.Request.Form[string.Concat(ID, "_hiddeninput").Replace("_", "$")];
            //Color = Page.Request.Form[string.Concat(ID, "_input").Replace("_", "$")];
        }

        protected override object SaveViewState()
        {
            //return base.SaveViewState();
            return (object)Color;
        }

        protected override void LoadViewState(object savedState)
        {
            //base.LoadViewState(savedState);
            Color = (string)savedState;
        }

        public bool LoadPostData(string postDataKey, NameValueCollection postData)
        {
            string PostedValue = postData[postDataKey];
            string val = Color;

            if (PostedValue == null || val != PostedValue)
            {
                Color = PostedValue;
                return true;
            }

            return false;
        }

        public void RaisePostDataChangedEvent()
        {
            OnColorChanged(EventArgs.Empty);
        }

        public void OnColorChanged(EventArgs e)
        {
            if (ColorChanged != null)
                ColorChanged(this, e);
        }

        protected override void Render(HtmlTextWriter output)
        {
            /* 
             Render HTML Tags Code:
            <div style="display:inline;">
            <div style="border:solid 1px #000;width:86px;float:left;"><label style="display:block;background-color:#000;width:80px;margin:3px;">&nbsp;</label></div>
            <img src="images/PaintBucket.png" alt="Color Picking" style="float:right;cursor:hand;"/>
            </div>
             */

            StringBuilder sb = new StringBuilder();

            sb.Append(string.Format(@"<div style=""display:inline;""><div style=""border:solid 1px #000;width:86px;float:left;""><label style=""display:block;background-color:{0};width:80px;margin:3px;"" id=""{1}"">&nbsp;</label></div>", Color, string.Concat(ID, "_input")));
            if (this.AutoPostBack)
            {
                sb.Append(string.Format(@"<img src=""{0}"" alt=""Color Picking"" style=""{4}"" onclick=""showColorPicker(this,document.getElementById('{1}'),document.getElementById('{2}'),{3});return false;""/></div>", PickerImageURL, string.Concat(ID, "_input"), string.Concat(ID, "_hiddeninput"), "true", DEFAULT_PICKERIMAGE_STYLE));
            }
            else
            {
                sb.Append(string.Format(@"<img src=""{0}"" alt=""Color Picking"" style=""{4}"" onclick=""showColorPicker(this,document.getElementById('{1}'),document.getElementById('{2}'),{3});return false;""/></div>", PickerImageURL, string.Concat(ID, "_input"), string.Concat(ID, "_hiddeninput"), "false", DEFAULT_PICKERIMAGE_STYLE));
            }
            output.Write(sb);

            output.WriteBeginTag("input");
            output.WriteAttribute("name", this.UniqueID);
            output.WriteAttribute("type", "text");
            output.WriteAttribute("size", "10");
            output.WriteAttribute("style", "display:none;");
            output.WriteAttribute("maxlength", "7");
            output.WriteAttribute("value", this.Color);

            if (this.ID != null)
                output.WriteAttribute("id", string.Concat(ID, "_hiddeninput"));

            output.Write(HtmlTextWriter.TagRightChar);
        }

        public static Color ConvertStringToColor(string colorString)
        {
            System.Drawing.Color color;
            if (colorString[0] == '#' && colorString.Length < 8)
            {
                string s = colorString.Substring(1);
                while (s.Length != 6)
                {
                    s = string.Concat("0", s);
                }
                int red = Convert.ToInt32(s.Substring(0, 2), 16);
                int green = Convert.ToInt32(s.Substring(2, 2), 16);
                int blue = Convert.ToInt32(s.Substring(4, 2), 16);
                color = System.Drawing.Color.FromArgb(red, green, blue);
            }
            else
            {
                color = System.Drawing.Color.FromName(colorString);
            }
            return color;
        }

        public static string ColorToString(Color color)
        {
            string result;
            if (color.IsKnownColor || color.IsNamedColor || color.IsSystemColor)
            {
                result = color.Name;
            }
            else
            {
                result = string.Concat("#", color.ToArgb().ToString("X").Substring(2));
            }
            return result;
        }
    }
}